import axios from "axios";
import { Loading,Message } from "element-ui"

const loading={
    //Loading实例
    loadingInstance:null,
    open(){
        if(this.loadingInstance === null){
            this.loadingInstance=Loading.service({
                target: ".main",
                text:"拼命加载中",
            });
        }
    },
    close(){
        //当加载实例不为空时候进行关闭
        if(this.loadingInstance !== null){
            this.loadingInstance.close();
        }
        this.loadingInstance = null;
    }
}   

// axios.get("./db.json").then(res=>{
//     console.log(res.data);
// })
//自封装axios
const request = axios.create({
    //给axios请求路径加上前缀
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 5000, //请求超时时间 5s
})
//请求拦截器和响应拦截器(注意一定要返回)
request.interceptors.request.use(config=>{
    loading.open();
    return config;
},error=>{
    loading.close();
    return Promise.reject(error);
})
request.interceptors.response.use(response=>{
    loading.close();
    //响应不正常，出现了异常
    const result = response.data
    if(result.code !== 2000){
        Message({
            message: result.msg,
            type: "warning",
            duration: 3*1000,
        });
    }
    return response;
},error=>{
    loading.close();
    //出现了错误  也可以获取状态码
    console.log(error.response);
    Message({
        message: error.message,
        type: "error",
        duration: 3*1000,
    });
    return Promise.reject(error);
})
// request.get("./db.json").then(res=>{
//     console.log(res.data);
// })
//导出封装对象
export default request;
